package light.head.controller.oa;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import light.head.constant.Msg;
import light.head.constant.Parm;
import light.head.constant.Sys;
import light.head.constant.Url;
import light.head.dao.oa.AuditStatusDAO;
import light.head.dao.oa.ProcessConfigDAO;
import light.head.dao.oa.VehicleApplyDAO;
import light.head.dao.oa.VehicleTypeDAO;
import light.head.dao.sys.MessageDAO;
import light.head.dao.sys.MessageTemplateDAO;
import light.head.dao.sys.OrganDAO;
import light.head.dao.sys.UserInfoDAO;
import light.head.enm.RESULT;
import light.head.framework.base.SupporterController;
import light.head.framework.entity.PageBean;
import light.head.model.AuditStatus;
import light.head.model.ProcessConfig;
import light.head.model.UserInfo;
import light.head.model.VehicleApply;
import light.head.model.VehicleApplyItem;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
@Controller
@RequestMapping(value = Url.C_VEHICLEAPPLY)
public class VehicleApplyController extends SupporterController{
	private VehicleApplyDAO vaDAO;
	private VehicleTypeDAO vtDAO;
	private AuditStatusDAO asDAO;
	private OrganDAO organDAO;
	private ProcessConfigDAO pcDAO;
	private UserInfoDAO userDAO;
	private MessageDAO msgDAO;
	private MessageTemplateDAO mtDAO;
	
	
	@RequestMapping(value = Url.INIT)
	public ModelAndView init(HttpServletRequest request, HttpServletResponse response) throws Exception{
		return new ModelAndView(Url.VEHICLEAPPLY_INIT);
	}
	
	@RequestMapping(value = Url.QUERY)
	public ModelAndView query(HttpServletRequest request, HttpServletResponse response) throws Exception {
		PageBean pb = createPageBean(request);
		Map<String, String> map = createQueryMapByParmName(request, Parm.DELETED,Parm.TITLE, Parm.TIME1, Parm.TIME2, Parm.STATUS);
		
		if (vaDAO.findByMap(cu_code(request), map, pb) == RESULT.SUCCESS) {
			// 讲对应的审核状态放到对应的
			VehicleApply va = null;
			for (Object o : pb.getResultList()) {
				va = (VehicleApply) o;
				va.setAuditStatusList(asDAO.findByBusinessMc(Sys.B_THREE, va.getCode()));
			}
		}
		request.setAttribute(Parm.PAGE_BEAN, pb);
		return new ModelAndView(Url.VEHICLEAPPLY_LIST);
	}
	
	@RequestMapping(value = Url.EDIT)
	public ModelAndView edit(Integer code,HttpServletRequest request, HttpServletResponse response) throws Exception{
		if(code != null){
			VehicleApply va = vaDAO.get(code);
			List<VehicleApplyItem> list = vaDAO.findApplyItem(code);
			va.setAdList(list);
			request.setAttribute(Parm.APPLY, va);
		}
		return new ModelAndView(Url.VEHICLEAPPLY_EDIT);
	}

	//保存申请单
	@Transactional
	@RequestMapping(value = Url.SAVE)
	public void save(VehicleApply apply, HttpServletRequest request, HttpServletResponse response) throws Exception {
		RESULT result = RESULT.ERROR;
		
		if (null == apply || null == apply.getAdList() || apply.getAdList().size() == 0 || apply.getTitle() == null) {
			print(response, Msg.PARAMETER_ERROR);
			return;
		}
		// 检查是否配置审核流程
		List<ProcessConfig> pcList = pcDAO.findByOcBusiness(organDAO.getRoot(cu_organCode(request)).getCode(), Sys.B_THREE);
		if (pcList == null || pcList.size() == 0 ) {
			print(response, Msg.EXISTS);
			return;	
		}
		// 检查是否有可以保存的明细在保存,至少有一条明细可以保存
		boolean ok = true;
		for (VehicleApplyItem Item : apply.getAdList()) {
			if (null != Item && null != Item.getVtc() && null != Item.getCount() && Item.getCount().intValue() > 0 ) {
				ok = false;
			}
		}
		if (ok) {
			print(response, Msg.PARAMETER_ERROR);
			return;
		}
		
		Integer code = null;
		if (apply.getCode() != null) {
			VehicleApply old = vaDAO.get(apply.getCode());
			old.setCu(cu_code(request));
			old.setTitle(apply.getTitle().length() > 100 ? apply.getTitle().substring(0, 99) : apply.getTitle());
			result = vaDAO.upd(old);
			code = old.getCode();
		} else {
			apply.setCu(cu_code(request));
			apply.setOc(cu_organCode(request));
			if (apply.getTitle().length() > 100)
			apply.setTitle(apply.getTitle().substring(0, 99));
			apply.setDeleted(false);
			apply.setCt(new Date());
			
			result = vaDAO.add(apply);
			code = apply.getCode();
		}
		if (RESULT.SUCCESS == result) {
			List<VehicleApplyItem> list = apply.getAdList();
			List<VehicleApplyItem> oldList = vaDAO.findApplyItem(apply.getCode());
			
			for (VehicleApplyItem pii : list) {
				if (null == pii.getCode()) {
					if (null != pii.getVtc() && null != pii.getCount() && pii.getCount().intValue() > 0 ) {
						pii.setVac(code);
						result = vaDAO.add(pii);
					}
				} else {
					if (null == pii.getCount() || pii.getCount().intValue() == 0 || null == pii.getVtc()) {
						result = vaDAO.del(pii);
						continue;
					}
					
					for (VehicleApplyItem old : oldList) {
						if (pii.getCode().intValue() == old.getCode().intValue() && (old.getCount().intValue() != pii.getCount().intValue())) {
							old.setCount(pii.getCount());
							old.setVtc(pii.getVtc());
							result = vaDAO.upd(old);
						}
					}
				}
			}
			
			int len = list.size();
			for (VehicleApplyItem old : oldList) {
				int i = 0;
				for (; i < len; i ++) {
					if (null != old.getCode() && old.getCode().intValue() == list.get(i).getCode().intValue())
						break;
				}
				if (i == len){
					result = vaDAO.del(old);
				}
			}
		if (RESULT.SUCCESS == result) {
			int i = 1;
			for (ProcessConfig pc : pcList) {
				AuditStatus au = new AuditStatus();
				au.setBusiness(Sys.B_THREE);
				au.setCt(new Date());
				au.setCu(cu_code(request));
				au.setOc(cu_organCode(request));
				au.setMc(apply.getCode());
				au.setRc(pc.getRc());
				au.setPcc(pc.getCode());
				au.setPc(pc.getPc());
				// 默认第一个审核节点的上一节点审核状态为1通过
				if (null != pc.getPc() && pc.getPc().intValue() == 1){
					au.setBeforeStatus(Sys.B_ONE);
				}
				if (null != pc.getPc() && pc.getPc().intValue() == 1 && null != cu_roleCode(request) && pc.getRc() == cu_roleCode(request)){
					au.setStatus(Sys.B_ONE);
					au.setAt(new Date());
					au.setAu(cu_roleCode(request));
					i++;
				}
				if(null != pc.getPc() && pc.getPc().intValue() == 2 && i == 2){
					au.setBeforeStatus(Sys.B_ONE);
				}
				result = asDAO.add(au);
			}
			// 消息通知审核人
			Integer rc = asDAO.findByBusinessOcMc(Sys.B_ONE, cu_organCode(request), apply.getCode());	// 获取该机构具有审核申请单的角色编号
			if (null != rc) {
				List<UserInfo> userList = userDAO.findByRoleRc(cu_organCode(request), rc);	// 获取有审核角色的所有用户
				List<Integer> rucs = new ArrayList<Integer>();
				for (UserInfo u : userList) {
					rucs.add(u.getCode());
				}
				String content = mtDAO.applyTofirst(apply, cu_realName(request));
				msgDAO.sendToUsers("【" + cu_realName(request) + "】提交申请待审核通知", content, cu_code(request), cu_organCode(request), rucs);
			}
		}
			print(response, Msg.SUCCESS);
		} else {
			print(response, Msg.ERROR);
			return;
		}
	}
	
	/** 下面几个方法是选择商品时使用 */
	@RequestMapping(Url.AID_INIT)
	public ModelAndView aidInit(HttpServletRequest request, HttpServletResponse response) throws Exception {
		request.setAttribute(Parm.INDEX, request.getParameter(Parm.INDEX));
		System.out.println(request.getParameter(Parm.INDEX));
		return new ModelAndView(Url.VEHICLEAPPLY_VEHICLE_INIT);
	}
	
	@RequestMapping(Url.AID_LIST)
	public ModelAndView aidList(HttpServletRequest request, HttpServletResponse response) throws Exception {
		PageBean pb = createPageBean(request);
		Map<String, String> map = createQueryMapByParmName(request, Parm.NAME, Parm.DELETED, Parm.OC,Parm.TYPE,Parm.SORT);
		vtDAO.findByMapOc(cu_organCode(request), map, pb);
		request.setAttribute(Parm.PAGE_BEAN, pb);
		return new ModelAndView(Url.VEHICLEAPPLY_VEHICLE_LIST);
	}

	@RequestMapping(value = Url.SHIELD)
	public void shield(HttpServletRequest request, HttpServletResponse response) throws Exception {
		String code = request.getParameter(Parm.CODE);
		if (!isNotNull(code)) {
			print(response, Msg.PARAMETER_ERROR);
			return;
		}
		VehicleApply va = vaDAO.get(Integer.parseInt(code));
		if (va == null) {
			print(response, Msg.NOT_FIND);
		} else {
			va.setDeleted(true);
			if (vaDAO.upd(va) == RESULT.SUCCESS) {
				print(response, Msg.SUCCESS);
			} else {
				print(response, Msg.ERROR);
			}
		}
	}
	
	
	@RequestMapping(value = Url.UN_SHIELD)
	public void unshield(HttpServletRequest request, HttpServletResponse response) throws Exception {
		String code = request.getParameter(Parm.CODE);
		if (!isNotNull(code)) {
			print(response, Msg.PARAMETER_ERROR);
			return;
		}
		VehicleApply va = vaDAO.get(Integer.parseInt(code));
		if (va == null) {
			print(response, Msg.NOT_FIND);
		} else {
			va.setDeleted(false);
			if (vaDAO.upd(va) == RESULT.SUCCESS) {
				print(response, Msg.SUCCESS);
			} else 
				print(response, Msg.ERROR);
		}
	}
	
	// 单个申请单详情
	@RequestMapping(value = Url.DETAIL)
	public ModelAndView detail(Integer code, HttpServletRequest request, HttpServletResponse response) throws Exception {
		if (null != code) {
			VehicleApply a = vaDAO.get(code);
			if (null != a) {
				a.setAuditStatusList(asDAO.findByBusinessMc(Sys.B_ONE, a.getCode()));
				List<VehicleApplyItem> list = vaDAO.findApplyItem(code);
				a.setAdList(list);
				request.setAttribute(Parm.APPLY, a);
			}
		}
		return new ModelAndView(Url.VEHICLEAPPLY_DETAIL);
	}
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	@Autowired	
	public void setVaDAO(VehicleApplyDAO vaDAO) {
		this.vaDAO = vaDAO;
	}
	@Autowired
	public void setAsDAO(AuditStatusDAO asDAO) {
		this.asDAO = asDAO;
	}
	@Autowired
	public void setOrganDAO(OrganDAO organDAO) {
		this.organDAO = organDAO;
	}
	@Autowired
	public void setPcDAO(ProcessConfigDAO pcDAO) {
		this.pcDAO = pcDAO;
	}
	@Autowired
	public void setUserDAO(UserInfoDAO userDAO) {
		this.userDAO = userDAO;
	}
	@Autowired
	public void setMsgDAO(MessageDAO msgDAO) {
		this.msgDAO = msgDAO;
	}
	@Autowired
	public void setMtDAO(MessageTemplateDAO mtDAO) {
		this.mtDAO = mtDAO;
	}
	@Autowired
	public void setvtDAO(VehicleTypeDAO vtDAO) {
		this.vtDAO = vtDAO;
	}
	
}
